package com.hontech.dapapp

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.hontech.dapapp.ui.BaseActivity
import com.hontech.dapapp.ui.dialog.runProg
import com.hontech.dapapp.utils.AppTask
import com.hontech.dapapp.utils.Pro
import com.hontech.dapapp.utils.onClick
import com.hontech.dapapp.utils.queryPro
import com.hontech.dapapp.utils.runOnUi

class ProFragment : Fragment() {

    private lateinit var mSwipe: SwipeRefreshLayout
    private lateinit var mRv: RecyclerView

    private val adapter = ProAdapter()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_pro, null)
        init(view)
        return view
    }

    private fun init(view: View) {
        mSwipe = view.findViewById(R.id.id_pro_swipe)
        mRv = view.findViewById(R.id.id_pro_rv)
        mRv.adapter = adapter

        mRv.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)

        mSwipe.setOnRefreshListener { runOnUi {

            update()
            mSwipe.isRefreshing = false
        } }

        AppTask.post { runOnUi { update() } }
    }

    private suspend fun update() {
        runProg("更新", "更新项目") {
            val list = queryPro()
            adapter.pros = list
            adapter.notifyDataSetChanged()
        }
    }
}

private class ProItem(view: View) : RecyclerView.ViewHolder(view) {

    private val tvName = view.findViewById<TextView>(R.id.id_item_pro_tv_name)
    private val tvDes = view.findViewById<TextView>(R.id.id_item_pro_tv_description)

    fun setUp(pro: Pro) {
        tvName.text = pro.name
        tvDes.text = pro.description
        itemView.onClick {
            BaseActivity.INSTANCE.replaceFragment2(R.id.id_main_frame_layout, HexFragment(pro))
        }
    }
}

private class ProAdapter : RecyclerView.Adapter<ProItem>() {

    var pros = arrayOf<Pro>()

    override fun getItemCount(): Int {
        return pros.size
    }

    override fun onBindViewHolder(holder: ProItem, position: Int) {
        holder.setUp(pros[position])
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProItem {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_pro, parent, false)
        return ProItem(view)
    }
}





